<?php

namespace app\controller\Api\V1\Client\Common;

use support\Request;
use support\Response;

class IpController
{
    /**
     * 获取客户端真实 IP 地址（兼容反向代理）
     *
     * @param Request $request
     * @return Response
     */
    public function getClientIp(Request $request): Response
    {
        $headers = [
            'x-forwarded-for',
            'x-real-ip',
            'client-ip',
            'x-client-ip',
            'x-cluster-client-ip',
        ];

        $ip = '0.0.0.0';

        foreach ($headers as $header) {
            $value = $request->header($header);
            if (!empty($value)) {
                // 如果有多个 IP，取第一个
                $ip = trim(explode(',', $value)[0]);
                break;
            }
        }

        if ($ip === '0.0.0.0') {
            $ip = $request->getRealIp() ?? '0.0.0.0';
        }

        return jsonRe([
            'ip' => $ip,
        ]);
    }
}
